package com.community.common.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.common.mapper.*;
import com.community.common.pojo.Constant;
import com.community.common.pojo.PageRequest;
import com.community.common.pojo.domain.*;
import com.community.common.pojo.dto.FriendUserCondition;
import com.community.common.pojo.dto.PublicUserCondition;
import com.community.common.pojo.response.CodeEnum;
import com.community.common.pojo.response.MyResponse;
import com.community.common.pojo.vo.FriendUserVo;
import com.community.common.pojo.vo.OwnFriendVo;
import com.community.common.pojo.vo.PublicUserVo;
import com.community.common.util.CommonUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 业主好友表 服务实现类
 * </p>
 *
 * @author superman
 * @since 2020-08-02
 */
@Service
public class OwnerFriendService extends ServiceImpl<OwnerFriendMapper, OwnerFriend> {

    @Resource
    private UserPermissionMapper userPermissionMapper;
    @Resource
    private PictureMapper pictureMapper;
    @Resource
    private OwnerHouseMapper ownerHouseMapper;
    @Resource
    private CameraMapper cameraMapper;
    @Resource
    private CommunityMapper communityMapper;
    @Resource
    private FriendHouseMapper friendHouseMapper;
    @Resource
    private FriendUserMapper  friendUserMapper;


    public List<FriendUserVo> queryByPageAll(PageRequest<FriendUserCondition> pageRequest, String communityId, String checkState) {
        PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        return friendUserMapper.queryByPage(pageRequest.getCondition(), communityId, checkState);
    }

    @Transactional
    public MyResponse saveOrUpdateOwnerFriend(OwnerFriend ownerFriend) {
        OwnerFriend ownerFriendQuery = new OwnerFriend();
        ownerFriend.setOpenId(ownerFriend.getOpenId());
        LambdaQueryWrapper<OwnerFriend> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isEmpty(ownerFriend.getId())) {
            queryWrapper.eq(OwnerFriend::getOpenId, ownerFriend.getOpenId());
            List<OwnerFriend> ownerFriends = baseMapper.selectList(queryWrapper);
            if (ownerFriends.size() > 1000) {
                return MyResponse.fail("不允许添加超过1000个好友");
            }
            String idStr = CommonUtil.getIdStr();
            ownerFriend.setId(idStr);
            ownerFriend.setCreateTime(LocalDateTime.now());
            ownerFriend.setUpdateTime(LocalDateTime.now());
            int insert = baseMapper.insert(ownerFriend);
            FriendHouse friendHouse = new FriendHouse();
            friendHouse.setFriendId(idStr).setHouseId(ownerFriend.getHouseId()).setCommunityId(ownerFriend.getCommunityId())
                    .setBuildingId(ownerFriend.getBuildingId()).setCreateTime(LocalDateTime.now());
            friendHouseMapper.insert(friendHouse);
            if (insert == 1) {
                List<String> ownerCommunityVos = ownerHouseMapper.selectCommunityIdByOpenId(ownerFriend.getOpenId());
                for (String communityId : ownerCommunityVos) {
                    LambdaQueryWrapper<Camera> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(Camera::getCommunityId, communityId);
                    List<Camera> cameras = cameraMapper.selectList(wrapper);
                    for (Camera camera : cameras) {
                        UserPermission userPermission = UserPermission.builder()
                                .relevanceId(ownerFriend.getId())
                                .idTable(1)
                                .communityId(String.valueOf(communityId))
                                .cameraId(camera.getId())
                                .currentAllow(0)
                                .targetAllow(1)
                                .commandStatus(Constant.COMMAND_INIT)
                                .startTime(LocalDateTime.now())
                                .endTime(LocalDateTime.now().plusYears(15))
                                .createTime(LocalDateTime.now())
                                .updateTime(LocalDateTime.now())
                                .build();
                        userPermissionMapper.insert(userPermission);
                    }
                }
            }
            return MyResponse.success();
        } else { // 修改信息
            OwnerFriend result = baseMapper.selectById(ownerFriend);
            if (ObjectUtils.isEmpty(result)) {
                return MyResponse.fail(CodeEnum.NOT_FOUND);
            }
            ownerFriend.setUpdateTime(LocalDateTime.now());
            int i = baseMapper.updateById(ownerFriend);
            if (i == 1) {
                List<String> ownerCommunityVos = ownerHouseMapper.selectCommunityIdByOpenId(ownerFriend.getOpenId());
                for (String communityId : ownerCommunityVos) {
                    LambdaQueryWrapper<Camera> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(Camera::getCommunityId, communityId);
                    List<Camera> cameras = cameraMapper.selectList(wrapper);
                    for (Camera camera : cameras) {
                        LambdaQueryWrapper<UserPermission> wrapper1 = new LambdaQueryWrapper<>();
                        wrapper1.eq(UserPermission::getRelevanceId, ownerFriend.getId()).eq(UserPermission::getCameraId, camera.getId())
                                .orderByDesc(UserPermission::getId);
                        List<UserPermission> userPermissions = userPermissionMapper.selectList(wrapper1);
                        if (CollectionUtils.isEmpty(userPermissions)) {
                            UserPermission userPermission = UserPermission.builder()
                                    .relevanceId(ownerFriend.getId())
                                    .idTable(1)
                                    .communityId(String.valueOf(communityId))
                                    .cameraId(camera.getId())
                                    .currentAllow(0)
                                    .targetAllow(1)
                                    .commandStatus(Constant.COMMAND_INIT)
                                    .startTime(LocalDateTime.now())
                                    .endTime(LocalDateTime.now().plusYears(15))
                                    .createTime(LocalDateTime.now())
                                    .updateTime(LocalDateTime.now())
                                    .build();
                            userPermissionMapper.insert(userPermission);
                        } else {
                            UserPermission userPermission = userPermissions.get(0);
                            userPermission.setCurrentAllow(0).setTargetAllow(1).setCommandStatus(Constant.COMMAND_INIT)
                                    .setStartTime(LocalDateTime.now()).setEndTime(LocalDateTime.now().plusYears(15))
                                    .setUpdateTime(LocalDateTime.now());
                            userPermissionMapper.updateById(userPermission);
                        }
                    }
                }
                return MyResponse.success();
            }
        }
        return MyResponse.fail();
    }

    public OwnFriendVo info(String id) {
        OwnerFriend ownerFriend = baseMapper.selectById(id);
        if (ownerFriend == null) {
            return null;
        }
        String pictureId = ownerFriend.getPictureId();
        OwnFriendVo ownFriendVo = new OwnFriendVo();
        try {
            BeanUtils.copyProperties(ownFriendVo, ownerFriend);
        } catch (Exception e) {
            log.error("info BeanUtils.copyProperties error ", e);
        }
        Picture picture = pictureMapper.selectById(pictureId);
        if (picture != null) {
            ArrayList<Picture> pictures = new ArrayList<>();
            pictures.add(picture);
            ownFriendVo.setPictureUrlList(pictures);
        }
        return ownFriendVo;
    }

    public void delete(Long id) {
        OwnerFriend ownerFriend = baseMapper.selectById(id);
        ownerFriend.setIsDelete(1);
        baseMapper.updateById(ownerFriend);

        //取消当前好友的相机权限 （逻辑删除的目的就是为了相机删除权限的时候 能正常查到数据）
        List<UserPermission> userPermissions = userPermissionMapper.selectByFriendId(String.valueOf(id));
        for (UserPermission userPermission : userPermissions) {
            userPermission.setCurrentAllow(1).setTargetAllow(0)
                    .setCommandStatus(Constant.COMMAND_INIT).setUpdateTime(LocalDateTime.now());
            userPermissionMapper.updateById(userPermission);
        }
    }

}
